import { useGlobalStore } from '../store/global';

let globalStore: any = null;

export default function request (
{
    url = '',
    data = {},
    method = 'POST',
    errorToast = true,
    contentTypeIsForm = false,
    showLoading,
    header = {},
    timeout = 10000,
    baseURL = '',
}:
{
    baseURL?: string; // 请求baseURL
    timeout?: number; // 请求超时的毫秒数
    url: string; // 请求url
    data?: Object|String|ArrayBuffer; // 请求body参数，post的时候传
    header?: any; // 请求头
    method?: "POST" | "GET"; // post | get
    errorToast?: boolean; // 是否请求失败后显示错误提示
    contentTypeIsForm?: boolean; // post时传，true"content-type"为"application/x-www-form-urlencoded"，false为"application/json"
    showLoading?: { // 是否显示loading，对应的是ElementUI的ElLoading.service参数，显示loading时一般传{}，使用默认参数
        title?: string;
        mask?: boolean;
    };
} = { url: '' }
) : Promise<any> {
	if (!globalStore) globalStore = useGlobalStore();
	if (!baseURL) baseURL = globalStore.baseUrl;
    if (url === '') return Promise.reject({errorMsg: '请求失败'});
	const token = uni.getStorageSync("TOKEN");
	const userId = uni.getStorageSync("USER_ID");
	if (!token || !userId) {
		uni.navigateTo({
			url: '/pages/login/login'
		});
	}
	header.token = token;
	header.userId = userId;
    if (showLoading) {
        uni.showLoading({
			title: showLoading.title || '加载中',
			mask: showLoading.mask || true,
		});
    }
    if (method === 'POST' && 'Content-Type' in header === false) {
        if (contentTypeIsForm) {
            header['Content-Type'] = 'application/x-www-form-urlencoded';
        } else {
            header['Content-Type'] = 'application/json';
        }
    }
    return new Promise(async (resolve, reject) => {
        try{
        	const { data: res }: any = await uni.request({
        		url: `${baseURL}${url}`,
        		method,
        		data,
        		header,
        		timeout,
        		dataType: 'json',
        	});
			// console.log("res: ", res);
			if (res.code != 0) {
				if (errorToast) {
					showRequestError({res});
				}
				reject(res);
			}
			showLoading && uni.hideLoading();
			resolve(res.data);
        } catch (e) {
        	//TODO handle the exception
			showLoading && uni.hideLoading();
			if (errorToast) {
				showRequestError({error: e});
			}
			reject(e);
        }
    });
};

// 请求失败时的提示
export const showRequestError = ({res, error} : {res?: any, error?: any} = {}) => {
    let errorMsg = '请求失败';
    if (res) {
        const code = res.code;
        errorMsg = res.errorMsg || res.msg;
        if (!errorMsg) {
            switch (code) {
                case 2:
                    errorMsg = '当前用户没有权限！';
                    break;
                case 30:
                    errorMsg = '请求资源无效，请联系管理员！';
                    break;
                case 1:
                    // errorMsg = '请重新登录';
                    router.push("/login").catch((error) => {
                        ElMessage.error(error);
                    });
                    return;
                default:
                    break;
            }
        }
        if (!errorMsg) {
            errorMsg = res.msg || res.errMsg || '请求失败'
        }
    } else if (error) {
        if (typeof error === 'string') {
            errorMsg = error;
        } else if (error.message && typeof error.message === 'string') {
            errorMsg = error.message;
        } else if (error.request && typeof error.request === 'object' && typeof error.request.statusText === 'string') {
            errorMsg = error.request.statusText;
        }
    }
	uni.showToast({
		title: errorMsg,
		icon: 'error',
	});
};